package com.gmss.crawler.module.publication.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmss.crawler.constants.Base;
import com.gmss.crawler.constants.Constants;
import com.gmss.crawler.enums.AcademicianEnum;
import com.gmss.crawler.enums.CommonEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmss.crawler.module.paper.domain.Paper;
import com.gmss.crawler.module.patent.domain.Patent;
import com.gmss.crawler.module.person.controller.PersonInfoController;
import com.gmss.crawler.module.person.service.IPersonInfoService;
import com.gmss.crawler.module.title.domain.PersonTitle;
import com.gmss.crawler.module.title.service.IPersonTitleService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.CollectionUtils;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import com.gmss.crawler.module.publication.service.IPublicationService;
import com.gmss.crawler.module.publication.domain.Publication;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import lombok.Data;

import javax.annotation.Resource;


/**
 * <p>
 * 出版物表 前端控制器
 * </p>
 *
 * @author Auto-generator
 * @since 2021-10-24
 */
@RestController
@RequestMapping("/publication")
public class PublicationController extends Base {

    @Resource
    private IPublicationService iPublicationService;
    @Resource
    private IPersonInfoService iPersonInfoService;
    @Resource
    private IPersonTitleService iPersonTitleService;

    /**
     * 通过id查询
     */
    @GetMapping("/getById/{id}")
    public String getById(@PathVariable(value = "id") Integer id) {
        return respJson(CommonEnum.SUCCESS, iPublicationService.getById(id));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public String save(@RequestBody Publication publication) {
        iPublicationService.save(publication);
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 通过id删除
     */
    @DeleteMapping("/deleteById/{id}")
    public String delete(@PathVariable(value = "id") String ids) {
        String[] idsStrs = ids.split(",");
        for (String id : idsStrs) {
            iPublicationService.removeById(Integer.parseInt(id));
        }
        return respJson(CommonEnum.SUCCESS);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public String updateById(@RequestBody Publication publication) {
        iPublicationService.updateById(publication);
        return respJson(CommonEnum.SUCCESS);
    }


    /**
     * 查询列表
     */
    @PostMapping("/list")
    public String list(@RequestBody PublicationReqVo publication) {
        final LambdaQueryWrapper<Publication> lambda = new QueryWrapper<Publication>().lambda();
        this.buildCondition(lambda, publication);
        return respJson(CommonEnum.SUCCESS, iPublicationService.list(lambda));
    }

    /**
     * 分页查询
     */
    @PostMapping("/page")
    public String page(@RequestBody PublicationReqVo pageParam) {

        final LambdaQueryWrapper<Publication> lambda = new QueryWrapper<Publication>().lambda();
        this.buildCondition(lambda, pageParam);
        final IPage<Publication> page = iPublicationService.page(new Page<>(Constants.PAGE_NO, Constants.PAGE_SIZE), lambda);
        return respJson(CommonEnum.SUCCESS, page);
    }

    /**
     * 从数据库导入到excel
     *
     * @param str
     * @return
     * @throws Exception
     */
    @PostMapping("/exportPublication")
    public String exportPublication(@RequestBody String str) throws Exception {
        if (StringUtils.isBlank(str))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        Map<String, Object> map = JSON.parseObject(str);
        if (MapUtils.isEmpty(map))
            return respJson(CommonEnum.PARAM_NULL_ERROR);

        if (!map.containsKey("filePath") || StringUtils.isBlank(map.get("filePath").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的路径不能为空！");
        }

        if (!map.containsKey("fileName") || StringUtils.isBlank(map.get("fileName").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称不能为空！");
        } else {
            String fileName = map.get("fileName").toString();
            String fileNamesuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if (!StringUtils.equalsAny(fileNamesuffix, "xlsx", "xls")) {
                return respJson(CommonEnum.PARAM_ERROR, "导出excel的文件名称后缀不正确，后缀应该为xlsx或xls ");
            }
        }

        if (!map.containsKey("exportType") || StringUtils.isBlank(map.get("exportType").toString())) {
            return respJson(CommonEnum.PARAM_ERROR, "导出类型(exportType)不能为空！0：院士信息，1：长江学者，2：杰出青年，3：百人计划");
        }

        String exportType = map.get("exportType").toString();
        List<Integer> list = new ArrayList<>();
        List<Publication> publicationList = new ArrayList<>();
        switch (exportType) {
            case "0":
                list = iPersonInfoService.getAcademician();
                map.put("personTitles", list);
                publicationList = iPublicationService.queryExportExcelData(map);
                break;
            case "1":
                list = new ArrayList<>();
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_SPECIAL.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_LECTURE.getCode());
                list.add(AcademicianEnum.CHANGJIANG_SCHOLAR_YOUTH.getCode());
                map.put("personTitles", list);
                publicationList = iPublicationService.queryExportExcelData(map);
                break;
            case "2":
                break;
            case "3":
                break;
            case "4":
                break;
            default:
                publicationList = iPublicationService.queryExportExcelData(map);
                break;

        }
        boolean bool = iPublicationService.writeExcel(map.get("filePath").toString(), map.get("fileName").toString(), publicationList);
        if (bool) {
            return respJson(CommonEnum.SUCCESS, "导出excel路径：" + map.get("filePath").toString() + File.separator + map.get("fileName").toString());
        } else {
            return respJson(CommonEnum.FAILURE);
        }
    }


    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<Publication> lambda, PublicationReqVo param) {
        if (null != param.getId()) {
            lambda.eq(Publication::getId, param.getId());
        }
        if (null != param.getPersonId()) {
            lambda.eq(Publication::getPersonId, param.getPersonId());
        }
        if (!StringUtils.isEmpty(param.getTitle())) {
            lambda.eq(Publication::getTitle, param.getTitle());
        }
        if (!StringUtils.isEmpty(param.getPublicationDate())) {
            lambda.eq(Publication::getPublicationDate, param.getPublicationDate());
        }
        if (!StringUtils.isEmpty(param.getPages())) {
            lambda.eq(Publication::getPages, param.getPages());
        }
        if (null != param.getLanguageStandard()) {
            lambda.eq(Publication::getLanguageStandard, param.getLanguageStandard());
        }
        if (!StringUtils.isEmpty(param.getAuthors())) {
            lambda.eq(Publication::getAuthors, param.getAuthors());
        }
        if (!StringUtils.isEmpty(param.getKeyword())) {
            lambda.eq(Publication::getKeyword, param.getKeyword());
        }
        if (!CollectionUtils.isEmpty(param.getCreateTimeList())) {
            lambda.ge(Publication::getCreateTime, param.getCreateTimeList().get(0));
            lambda.le(Publication::getCreateTime, param.getCreateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getCreateUser())) {
            lambda.eq(Publication::getCreateUser, param.getCreateUser());
        }
        if (!CollectionUtils.isEmpty(param.getUpdateTimeList())) {
            lambda.ge(Publication::getUpdateTime, param.getUpdateTimeList().get(0));
            lambda.le(Publication::getUpdateTime, param.getUpdateTimeList().get(1));
        }
        if (!StringUtils.isEmpty(param.getUpdateUser())) {
            lambda.eq(Publication::getUpdateUser, param.getUpdateUser());
        }
        lambda.orderBy(true, false, Publication::getId);
    }


    /**
     * 请求model
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    private static class PublicationReqVo extends Publication {
        private List<String> createTimeList; // 创建时间起止
        private List<String> updateTimeList; // 更新时间起止
    }


}
